package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.SysLogService;
import com.itheima.pojo.SysLog;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect//表示当前是个切面类
public class LogAop {
    /*@Pointcut("")
    public void pt() {}
*/
    @Autowired
    private HttpServletRequest request;
    @Reference
    private SysLogService sysLogService;

    private Date startTime;//访问时间
    private Class excutionClass;//访问类
    private Method excutionMethod;//访问方法

    //主要获取访问时间、访问的类、访问的方法
    @Before("execution(* com.itheima.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {
        startTime  = new Date();
        //获取访问的类

         excutionClass = jp.getTarget().getClass();
        //获取方法
        String methodName = jp.getSignature().getName();
        //获取方法的参数
        Object[] args = jp.getArgs();
        //判断参数是否为空
        if (args == null || args.length == 0) {
            excutionMethod = excutionClass.getMethod(methodName);
        } else {
            //有参数，获取所有参数的类型放在一个class数组中
            Class[] classArgs = new Class[args.length];
            for (int i = 0; i < args.length; i++) {
                classArgs[i] = args[i].getClass();
            }

            excutionMethod  = excutionClass.getMethod(methodName,classArgs);
        }
        // 主要获取日志中其它信息，时长、ip、url...

    }

    // 主要获取日志中其它信息，时长、ip、url...
    @After("execution(* com.itheima.controller.*.*(..))")
    public void doAfter(JoinPoint jp){
        //获取类上的@RequestMapping对象
        if(excutionClass!= LogAop.class&&excutionMethod!=null&&excutionClass!=null&&excutionClass!=SysLogController.class){
            RequestMapping classAnnotation = (RequestMapping) excutionClass.getAnnotation(RequestMapping.class);
            if(classAnnotation!=null){
                //获取方法上的@RequestMapping对象
                RequestMapping methodAnnotation = excutionMethod.getAnnotation(RequestMapping.class);
                if(methodAnnotation!=null){
                    String url = "";//它的值就应该是类上的RequestMapping的value值+方法上的RequestMapping的Value值
                    url = classAnnotation.value()[0]+methodAnnotation.value()[0];
                    SysLog sysLog = new SysLog();
                    //获取访问时长
                    long executionTime = new Date().getTime() - startTime.getTime();
                    sysLog.setExecutionTime(executionTime);
                    sysLog.setUrl(url);
                    //获取ip
                    String ip = request.getRemoteAddr();
                    System.out.println("ip = " + ip);
                    sysLog.setIp(ip);
                    //获取用户名username
                    // 可以通过securityContext获取，也可以从request.getSession中获取
                    SecurityContext context = SecurityContextHolder.getContext();
                    User user = (User)context.getAuthentication().getPrincipal();
                   sysLog.setUsername(user.getUsername());
                   sysLog.setMethod("[类名]"+excutionClass.getName()+"[方法名]"+excutionMethod.getName());
                    sysLog.setVisitTime(startTime);
                    //将其保存到数据库中,调用service层中的方法
                    sysLogService.save(sysLog);
                }
            }
        }

    }

}
